package com.pro.common.modules.service.dependencies.config.component;

import com.pro.common.api.enums.EnumSysRole;
import com.pro.common.api.model.ILoginInfo;
import com.pro.common.api.model.LoginInfo;
import com.pro.framework.api.util.JSONUtils;
import com.pro.framework.web.config.ILoginInfoArgumentResolver;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.ModelAndViewContainer;

@Slf4j
@Service
public class LoginInfoArgumentResolver implements ILoginInfoArgumentResolver {

    public static final LoginInfo LOGIN_INFO_ANONYMOUS = new LoginInfo(EnumSysRole.ANONYMOUS, -9999L, null, null);

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return ILoginInfo.class.isAssignableFrom(parameter.getParameterType());
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {
        // 从请求头中获取用户信息
        String userInfoJson = webRequest.getHeader(ILoginInfo.HEADER_KEY_MAIN);
        String role = webRequest.getHeader(ILoginInfo.HEADER_KEY_ROLE);
        ILoginInfo loginInfo;
        if (userInfoJson == null) {
            loginInfo = LOGIN_INFO_ANONYMOUS;
//            throw new IllegalArgumentException(ILoginInfo.HEADER_KEY + " header is missing");
        } else {
            //noinspection unchecked
            Class<? extends ILoginInfo> loginInfoClass = ILoginInfo.class.equals(
                    parameter.getParameterType()) ? LoginInfo.class : (Class<? extends ILoginInfo>) parameter.getParameterType();

            // 将 JSON 反序列化为 LoginInfo 对象
            loginInfo = getLoginInfo(userInfoJson, loginInfoClass, role);
        }
//        log.info("LoginInfoContext.set {}",loginInfo.toString());
//        LoginInfoContext.set(loginInfo);
        return loginInfo;
    }

    public ILoginInfo getLoginInfo(String userInfoJson, Class<? extends ILoginInfo> loginInfoClass, String role) {
        return JSONUtils.fromString(userInfoJson, loginInfoClass);
    }
}
